package com.excel;

import java.awt.Color;

import jxl.format.Alignment;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Border;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormats;
import jxl.write.VerticalAlignment;
import jxl.write.WritableCellFormat;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.dom4j.Document;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

public class TableExcelWriter extends ExcelWriter {
    /**
     * head and data
     */
    String htmlTable;
    TableRow[] trList;
   
    
    public static Node extractCondition(NodeList list, String id) {
    	int size = list.size();
    	Node aNode = null;
    	for(int i=0; i<size; i++) {
    	    Node node = list.elementAt(i);
    	    if(node instanceof Div) {
    		Div divTag = (Div)node;
    		String anId = divTag.getAttribute("id");
     		if(anId!=null && anId.equalsIgnoreCase(id)) {
     			aNode = node;
    		    return aNode;
    		}
    	    }
    	}
    	
    	return aNode;
    	
        }

    
    public static Node extractTable(NodeList list, String id) {
    	int size = list.size();
    	Node node = null;
    	Node aNode = null;
    
    	aNode = list.elementAt(0);    
    	return aNode;
    	
        }

    
    public TableExcelWriter(String fileName, String htmlTable, String condition) {
	super(fileName);
	// 删除前一天的
	// TODO
	// File directoryFile = new File("");
	// File files[] = directoryFile.listFiles();
	this.condition = condition;
	this.htmlTable = htmlTable;
    }

    private TableTag extracTable(NodeList alist) {
	NodeClassFilter rorFilter = new NodeClassFilter(TableTag.class);
	// 得到所有经过过滤的标签
	NodeList list = alist.extractAllNodesThatMatch(rorFilter, true);
	for (int i = 0; i < list.size(); i++) {
	    return (TableTag) list.elementAt(i);
	}
	return null;
    }

    /**
     * 通过HTML Table设置配置信息
     */
    public void initConfig() {
	// data
	// for test 数据从地三行开始
	Document document = null;

	Lexer lexer = new Lexer(htmlTable);
	Parser parser = new Parser(lexer);
	TableRow[] ast2 = null;

	try {
	    NodeList list = parser.parse(null);
	    TableTag aTableTag = extracTable(list);
	    ast2 = aTableTag.getRows();
	    this.trList = ast2;
	    dataRowCount = this.trList.length;
	} catch (ParserException e1) {
	    e1.printStackTrace();
	}

    }

    protected void drawRect(BorderLineStyle style, Colour BorderColor, Colour bgColor) throws WriteException {
    }

    protected void writeTableHead(MergedColumns mergedColumns) {
    }

    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
	try {
	    Integer.parseInt(value);
	    return true;
	} catch (NumberFormatException e) {
	    return false;
	}
    }

    /**
     * 判断字符串是否是浮点数
     */
    public static boolean isDouble(String value) {
	try {
	    Double.parseDouble(value);
	    if (value.contains("."))
		return true;
	    return false;
	} catch (NumberFormatException e) {
	    return false;
	}
    }

    /**
     * 判断字符串是否是数字
     */
    public static int getNumberFlag(String value) {
	int falg = 0;
	if (isDouble(value)) {
	    falg = 1;
	} else if (isInteger(value)) {
	    falg = 2;
	}
	return falg;
    }

    /**
     * 起始位置从(2,0)开始
     * 
     * @param resultSet
     */
    protected void writeDataSheet() {
	int rows = 0;
	int colIndex = this.tableXIndex + 1;
	MyTable table = getTable();
	//标题列颜色
	String color = "#eeeeee";
	boolean isComplexHead = false;
	// 1.0取字段列表

	int numColumns = 0;
	//判断猎头是否为两行

	    // 逐行写数据
	    for (int i = 0; i < dataRowCount; i++) {
		colIndex = this.tableXIndex;
		TableRow trElement = this.trList[i];

		TableColumn[] tdElementsList = trElement.getColumns();
		numColumns = tdElementsList.length;
		for (int j = 0; j < numColumns; j++) {		 
		    TableColumn tdElement = tdElementsList[j];		   
		    String colsSpanStr = tdElement.getAttribute("colspan");
		    int colLen = colsSpanStr == null ? 1 : Integer.parseInt(colsSpanStr);		   
		    if (colLen > 1) {
		    isComplexHead = true;
		    break;
		    }		    				   
		}
		
	    }
	
	
	try {
	    // 逐行写数据
	    for (int i = 0; i < dataRowCount; i++) {
		colIndex = this.tableXIndex;
		TableRow trElement = this.trList[i];

		TableColumn[] tdElementsList = trElement.getColumns();
		numColumns = tdElementsList.length;
		for (int j = 0; j < numColumns; j++) {

		    // td
		    TableColumn tdElement = tdElementsList[j];
		    
		    NodeList childList = tdElement.getChildren();
		    String contentString = childList == null ? "" : childList.asString().replaceAll("&nbsp;", "");
		    String colsSpanStr = tdElement.getAttribute("colspan");
		    int colLen = colsSpanStr == null ? 1 : Integer.parseInt(colsSpanStr);
		    int flag = getNumberFlag(contentString);
		    BorderLineStyle style = BorderLineStyle.THIN;
		    Colour BorderColor = Colour.BLACK;

		    WritableCellFormat alignStyle = new WritableCellFormat(); // 单元格样式
		  
		    alignStyle.setVerticalAlignment(VerticalAlignment.CENTRE);// 设置对齐方式
		    alignStyle.setBorder(Border.TOP, style, BorderColor);// 设置边框的颜色和样式
		    alignStyle.setBorder(Border.LEFT, style, BorderColor);// 设置边框的颜色和样式
		    alignStyle.setBorder(Border.RIGHT, style, BorderColor);// 设置边框的颜色和样式
		    alignStyle.setBorder(Border.BOTTOM, style, BorderColor);// 设置边框的颜色和样式
		   

		    //如果是标题列，加背景, 设置默认对齐方式
		    //单元格对齐属性
		    
		    String align = tdElement.getAttribute("align");
		    
		    Alignment dataAlignment = Alignment.LEFT;
		    Alignment titleAlignment = Alignment.CENTRE;
		    
		    if(align != null && align.equalsIgnoreCase("center")) {
		    	dataAlignment = Alignment.CENTRE;
		    	titleAlignment =  Alignment.CENTRE;
		    }else if(align != null && align.equalsIgnoreCase("right")) {
		    	dataAlignment = Alignment.RIGHT;
		    	titleAlignment =  Alignment.RIGHT;
		    }else if(align != null && align.equalsIgnoreCase("left")) {
		    	dataAlignment = Alignment.LEFT;
		    	titleAlignment =  Alignment.LEFT;
		    }
		    
		    
		    if(isComplexHead) {
		    	if(i<2) {
		    		//标题
		    		alignStyle.setBackground(Colour.GREY_25_PERCENT);  //TAN
		    		alignStyle.setAlignment(titleAlignment); // 设置对齐方式
		    	}else {
		    		//数据
		    		alignStyle.setAlignment(dataAlignment); // 设置对齐方式
		    	}
		    	//取得宽度
		    	if(i==1) {
	    		String width =  tdElement.getAttribute("width");
	    		if(width == null) {
	    			width = "60";
	    		}else if(width.indexOf("%")>-1){
	    			width = width.replace("%", "");
	    			width = ""+ Integer.parseInt(width)*750;
	    		}else {
	    			width = width.replace("px", "");
	    		}
	    		s.setColumnView(j, Integer.parseInt(width)/5);
		    	}
		    }else {
		    	if(i==0) {
		    		//标题
		    		//取得宽度
		    		String width =  tdElement.getAttribute("width");
		    		if(width == null) {
		    			width = "60";
		    		}else if(width.indexOf("%")>-1){
		    			width = width.replace("%", "");
		    			width = ""+ Integer.parseInt(width)*750;
		    		}else {
		    			width = width.replace("px", "");
		    		}
		    		s.setColumnView(j, Integer.parseInt(width)/5);
		    		alignStyle.setAlignment(titleAlignment); // 设置对齐方式
		    		alignStyle.setBackground(Colour.GREY_25_PERCENT);
		    	}else {
		    		//数据
		    		alignStyle.setAlignment(dataAlignment); // 设置对齐方式
		    	}
		    }
		    if (flag == 1) {
				WritableCellFormat cf2 = new WritableCellFormat(NumberFormats.FLOAT);
				cf2.setAlignment(Alignment.LEFT);
				Number n = new Number(colIndex, tableYIndex + i, Double.parseDouble(contentString), cf2);
				n.setCellFormat(alignStyle);
				s.addCell(n);
			    } else if (flag == 2) {
				WritableCellFormat cf2 = new WritableCellFormat(NumberFormats.INTEGER);
				Number n = new Number(colIndex, tableYIndex + i, Integer.parseInt(contentString), cf2);
				n.setCellFormat(alignStyle);
				s.addCell(n);
			    } else {
				Label label = new Label(colIndex, tableYIndex + i, contentString);

				label.setCellFormat(alignStyle);
				s.addCell(label);
			    }
		    
		    if (colLen > 1) {		
				s.mergeCells(colIndex, tableYIndex + i, colIndex + colLen - 1, tableYIndex + i);				
			}
		    colIndex += colLen;
		}

	    }
	} catch (RowsExceededException e) {
	    e.printStackTrace();
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	} catch (WriteException e) {
	    e.printStackTrace();
	}

    }

    public MergedColumns getMergedColumns() {
	return mergedColumns;
    }

    public void setMergedColumns(MergedColumns mergedColumns) {
	this.mergedColumns = mergedColumns;
    }


	
    

}
